#include <iostream>
#include <string>
//#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"

using namespace std;
int main(int argc,char* argv[])
{
	if(argc!=3)
	{
		std::cerr<<"Usage:"<<argv[0]<<" server-ip  server-port"<<std::endl;
		exit(4);
	};
	std::string server_ip =argv[1];
	uint16_t server_port =stoi(argv[2]);//取出参数行列表的数据
	int sockfd=socket (AF_INET,SOCK_DGRAM,0);
	if(sockfd<0)
	{
		LOG(FATAL,"client socket create err\n");
		exit(5);
	};
	struct sockaddr_in server;//服务端地址
	memset(&server,0,sizeof(server));
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = inet_addr(server_ip.c_str());
	server.sin_port = htons(server_port);
	while(1)
	{
		std::cout<<"Please Enter#";
		std::string message;
		std::getline(std::cin,message);
		int n =sendto(sockfd,message.c_str(),message.size(),0,reinterpret_cast<struct sockaddr*>(&server),sizeof(server));
		if(n>0)
		{
			sockaddr_in temp;//向我发送数据的进程的地址
			socklen_t len =sizeof(temp);
			char buffer[1024];
			int m =recvfrom(sockfd,buffer,sizeof(buffer)-1,0,reinterpret_cast<struct sockaddr*>(&temp),&len);
			if(m>0)
			{
				buffer[m]=0;
				std::cout<<buffer<<std::endl;
			}
			else
			{
				LOG(DEBUG,"Client recvfrom err\n");
                       		 break;

			};

		}
		else
		{
			LOG(DEBUG,"Client sendto err\n");
			break;
		};

	}





	close(sockfd);
	return 0;
};
